package org.example.interceptor;

import com.alibaba.fastjson.JSON;

import org.example.domain.Result;
import org.example.redis.util.RedisUtils;
import org.example.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 头部拦截处理器，用于提取里面的token信息，并进行验证，可以有效记录用户的身份信息
 * @author hxy
 * @date 2021/1/12
 */
public class HeaderTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //参数中的token
        String tokenStr = request.getParameter("token");
        //请求头的token
        String token = request.getHeader("token");

        if(StringUtils.isEmpty(tokenStr) && StringUtils.isEmpty(token)){
            dealErrorReturn(request,response, Result.noToken("缺少token，无法验证"));
            return false;
        }

        if (!StringUtils.isEmpty(tokenStr)){
            token = tokenStr;
        }

        String userId = "";
        try{
            userId = JwtTokenUtil.verifyToken(token);
        }catch (Exception e){
            dealErrorReturn(request,response, Result.noToken("凭证过期"));
            return false;
        }

        /* 根据userId判断redis中是否存在此id,主要用来判断用户是否注销*/
        /*if(redisUtils.sHasKey("user_login_info",userId)){

            return true;
        }else {
            dealErrorReturn(request,response,Result.noToken("登录已失效"));
            return false;
        }*/
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    //检测到没有token，直接返回不验证
    //为什么不用Result，因为在prehandler没有对应的返回类型，只能通过响应对象返回
    public void dealErrorReturn(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Result result){
        String json = JSON.toJSONString(result);
        PrintWriter printWriter = null;
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try{
            printWriter =httpServletResponse.getWriter();
            printWriter.write(json);
        }catch (IOException ioe){
            //TODO 日志输出
        }
        finally {
            if(printWriter != null){
                printWriter.close();
            }
        }
    }
}
